package sunsun.xiaoli.jiarebang.device;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import com.itboye.pondteam.base.BaseActivity;
import com.itboye.pondteam.bean.DeviceDetailModel;
import com.itboye.pondteam.bean.DeviceListBean;
import com.itboye.pondteam.custom.swipemenulistview.SwipeMenuCreator;
import com.itboye.pondteam.custom.swipemenulistview.SwipeMenuItem;
import com.itboye.pondteam.interfaces.PermissionListener;
import com.itboye.pondteam.presenter.UserPresenter;
import com.itboye.pondteam.utils.Const;
import com.itboye.pondteam.utils.SPUtils;
import com.itboye.pondteam.utils.languageutil.LocaleManager;
import com.itboye.pondteam.utils.loadingutil.MAlert;
import com.itboye.pondteam.volley.ResultEntity;
import org.json.JSONException;
import org.json.JSONObject;
import sunsun.xiaoli.jiarebang.BuildConfig;
import sunsun.xiaoli.jiarebang.R;
import sunsun.xiaoli.jiarebang.adapter.DeviceListForPondLinkAdapter;
import sunsun.xiaoli.jiarebang.app.App;
import sunsun.xiaoli.jiarebang.beans.PushModel;
import sunsun.xiaoli.jiarebang.custom.VpSwipeRefreshLayout;
import sunsun.xiaoli.jiarebang.device.pondteam.ActivityPondDeviceDetail;
import sunsun.xiaoli.jiarebang.device.pondteam.AddPondDevice;
import sunsun.xiaoli.jiarebang.logincontroller.LoginController;
import sunsun.xiaoli.jiarebang.logincontroller.LoginedState;
import sunsun.xiaoli.jiarebang.logincontroller.UnLoginState;
import sunsun.xiaoli.jiarebang.popwindow.SureDeleteDialog;
import sunsun.xiaoli.jiarebang.utils.ComparePondFilterVersion;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.pondteam.utils.EmptyUtil.getSp;
import static sunsun.xiaoli.jiarebang.utils.ComparePondFilterVersion.subVersion;


/**
 */
@SuppressLint("NewApi")
public class DeviceActivity extends BaseActivity implements Observer, SwipeRefreshLayout.OnRefreshListener {
    App mApp;
    GridView mListView;
    private ProgressDialog mProgressDialog;
    ImageView img_back;
    RelativeLayout nodata;

    RelativeLayout relyout;
    VpSwipeRefreshLayout swipe_layout2;
    ImageView img_right;
    TextView txt_title;
    RelativeLayout re_addnew;
    TextView txt_add_jieshao, txt_pondlink;
    public String uid = "";
    UserPresenter userPresenter;
    UserPresenter userPresenterOldHost;
    public ArrayList<DeviceListBean> arrayList = new ArrayList<>();
    public int position;
    TextView txt_exist, txt_ceshu;
    private ProgressDialog loadingDialog;
    public DeviceListBean mSelectDeviceInfo;
    //    private ArrayList<HashMap<String, Object>> listItems;
    private String currentDid, currentType;
    private SureDeleteDialog loadingDialogDelete;
    PushModel ummessage;
    VpSwipeRefreshLayout swipe_layout;
    public String extra;
    View footerView;
    private SimpleAdapter listItemsAdapter;
    private DeviceDetailModel deviceDetailModel;
    private String htmlText, htmlText2;
    private String get_onLine_state = "getOnlineState";


    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
    private BufferedOutputStream ouStream;
    private BufferedInputStream inStream;
    ScrollView scroll;
    private BaseAdapter deviceListAdapter;

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_device_pondlink);
        deviceListAdapter = new DeviceListForPondLinkAdapter(arrayList, this);
        mApp = (App) getApplication();
        mApp.mDeviceUi = this;
        txt_ceshu.setVisibility(View.VISIBLE);
//        footerView = LayoutInflater.from(this).inflate(R.layout.device_list_footer, null);
//        nodata = footerView.findViewById(R.id.nodata);
//        btn_addnew = footerView.findViewById(R.id.btn_addnew);
//        btn_addnew.setOnClickListener(this);
//        txt_add_jieshao = footerView.findViewById(R.id.txt_add_jieshao);
//        txt_pondlink = footerView.findViewById(R.id.txt_pondlink);
        ummessage = (PushModel) getIntent().getSerializableExtra("ummessage");
        if (ummessage != null) {
//            showPushMessage();
        }
        img_right.setBackgroundResource(R.drawable.menu);
        txt_title.setText(getString(R.string.myadvice));
        userPresenter = new UserPresenter(this);
        userPresenterOldHost = new UserPresenter(this);
        uid = getSp(Const.UID);
        //设置向下拉多少出现刷新
        swipe_layout.setDistanceToTriggerSync(150);
        swipe_layout.setColorSchemeColors(getResources().getColor(R.color.main_green));
        swipe_layout.setOnRefreshListener(this);
        swipe_layout.setRefreshing(true);
        mListView.setAdapter(deviceListAdapter);
        img_back.setVisibility(View.GONE);
        txt_exist.setText(getString(R.string.exist_login));
        initSwipListView();
        mApp.mDeviceUi = this;
//        NotifycationCheck.checkAndOpennotifycation(this);
        htmlText = getString(R.string.tips_detail);
        if (BuildConfig.APP_TYPE.equalsIgnoreCase("pondteam") ||
                BuildConfig.APP_TYPE.equalsIgnoreCase("pondlink")) {
            htmlText2 = getStringValue(R.string.pondLink_support);
            txt_pondlink.setText(getClickableSpan());
            txt_pondlink.setMovementMethod(LinkMovementMethod.getInstance());
            txt_ceshu.setVisibility(View.GONE);
            userPresenter.setBaseUrl(Const.pondlink_wrapUrl);
        } else if (BuildConfig.APP_TYPE.equalsIgnoreCase("小鲤智能") || BuildConfig.APP_TYPE.equalsIgnoreCase("水族之家")) {
            initHeader();
        }
        txt_add_jieshao.setText(Html.fromHtml(htmlText, source -> {
            int id = Integer.parseInt(source);
            Drawable drawable = ContextCompat.getDrawable(DeviceActivity.this, id);//getResoueces.getDrawable(id,null)已经过时
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            return drawable;
        }, null));
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setOnKeyListener((dialog, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mProgressDialog.dismiss();
            }
            return false;
        });

        //列表项短按键处理
        mListView.setOnItemClickListener((parent, view, position, id) -> {
//            if (listItems.get(position - 1).get("ItemDid").toString().substring(4, listItems.get(position - 1).get("ItemDid").toString().length()).startsWith("S10")) {
//                //宠物喂食器调跳转
//                startActivity(new Intent(DeviceActivity.this, PetFeederDetailActivity.class).putExtra("id", "3").putExtra("did", "S100000000001"));
//                return;
//            }

            // TODO 修正有Header的ListView的position的BUG
//            int headerViewsCount = mListView.getHeaderViewsCount();//得到header的总数量
            int headerViewsCount = 0;//得到header的总数量
//得到新的修正后的position
            DeviceActivity.this.position = position - headerViewsCount;
            currentDid = arrayList.get(DeviceActivity.this.position).getDid();
            mSelectDeviceInfo = arrayList.get(DeviceActivity.this.position);

            currentType = arrayList.get(DeviceActivity.this.position).getDevice_type();
            extra = arrayList.get(DeviceActivity.this.position).getExtra();
            loadingDialog = new ProgressDialog(DeviceActivity.this);

            if (!BuildConfig.APP_TYPE.equals("pondTeam")) {
//                if (currentDid.startsWith("S16")) {
//                    Intent intent = PlantWallActivity.createIntent(this);
//                    intent.putExtra("title", mSelectDeviceInfo.getDevice_nickname());
//                    intent.putExtra("did", mSelectDeviceInfo.getDid());
//                    intent.putExtra("id", mSelectDeviceInfo.getId());
//                    intent.putExtra("hasPsw", true);//无密码则应该重新进入插入密码
//                    intent.putExtra("detailModel", new DeviceDetailModel());
//                    startActivity(intent);
//                    return;
//                }
                if (!mSelectDeviceInfo.getDevice_type().equals("chiniao_wifi_camera") && mSelectDeviceInfo.getIs_disconnect() != 0) {
                    MAlert.alert(getString(R.string.disconnect));
                    return;
                }

                if (!currentDid.toLowerCase().startsWith("SCHD".toLowerCase())) {
                    loadingDialog.setMessage(getString(R.string.requesting));
                    loadingDialog.setCanceledOnTouchOutside(false);
                    loadingDialog.show();
                    userPresenter.getDeviceDetailInfo(currentDid, getSp((Const.UID)));
                } else {
                    String psw = "";
                    try {
                        JSONObject jsonObject = new JSONObject(extra);
                        psw = jsonObject.getString("pwd");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

//                    Intent intent = new Intent(DeviceActivity.this, VideoActivity.class);
//                    intent.putExtra("cameraDid", currentDid);
//                    intent.putExtra("cameraPsw", psw);
//                    intent.putExtra("isMasterDevice", true);
//                    intent.putExtra("model", mSelectDeviceInfo);
//                    startActivity(intent);
                }
            } else {
                if (currentDid.startsWith("S01")) {
                    loadingDialog.setMessage(getString(R.string.requesting));
                    loadingDialog.setCanceledOnTouchOutside(false);
                    loadingDialog.show();
                    userPresenter.getDeviceDetailInfo(currentDid, "0", get_onLine_state);
                } else {
                    MAlert.alert(getString(R.string.deviceid_error));
                }
            }
        });

        // 列表项长按键处理
        mListView.setOnItemLongClickListener((parent, view, position, id) -> {
            longClickEvent(position);
            return true;
        });
        LoginController.setLoginState(new LoginedState());
//        //        //获取相册中的图片
//        if (Build.VERSION.SDK_INT >= 23) {//判断当前系统是不是Android6.0
//            requestRuntimePermissions(PERMISSIONS_STORAGE, new PermissionListener() {
//                @Override
//                public void granted() {
//                    //权限申请通过
//                }
//
//                @Override
//                public void denied(List<String> deniedList) {
//                    //权限申请未通过
//                    boolean hasGranted = false;
//                    for (String denied : deniedList) {
//                        if (denied.equals(PERMISSIONS_STORAGE[0])) {
//                            hasGranted = false;
//                            openAppDetails(getString(R.string.need_read_access));
//                            break;
//                        } else {
//                            hasGranted = true;
//                        }
//                    }
//                }
//            });
//        } else {
//        }
//        throw new RuntimeException("测试异常");
    }

    private void requestPer() {
        if (Build.VERSION.SDK_INT >= 23) {//判断当前系统是不是Android6.0
            requestRuntimePermissions(PERMISSIONS_STORAGE, new PermissionListener() {
                @Override
                public void granted() {
                    //权限申请通过
                }

                @Override
                public void denied(List<String> deniedList) {
                    if (deniedList != null && deniedList.size() > 0) {
                        openAppDetails(getString(R.string.need_access));
                    }
//                            //权限申请未通过
//                            for (String denied : deniedList) {
//                                if (denied.equals(PERMISSIONS_STORAGE[0])) {
//                                    break;
//                                } else {
//
//                                }
//                            }
                }
            });
        } else {
        }
    }

    private void longClickEvent(int position) {
//        if (BuildConfig.APP_TYPE.equalsIgnoreCase("pondteam") ||
//                BuildConfig.APP_TYPE.equalsIgnoreCase("pondlink") ||
//                BuildConfig.APP_TYPE.equalsIgnoreCase("小绵羊智能")) {
        DeviceActivity.this.position = position;
//        } else {
//            DeviceActivity.this.position = position - 1;
//        }
        mSelectDeviceInfo = arrayList.get(DeviceActivity.this.position);
        mApp.mEditDeviceInfo = mSelectDeviceInfo;
        Intent mainIntent = new Intent(DeviceActivity.this,
                EditDeviceActivity.class);
        mainIntent.putExtra("id", mSelectDeviceInfo.getId());
        mainIntent.putExtra("type", mSelectDeviceInfo.getDevice_type());
        DeviceActivity.this.startActivity(mainIntent);
    }

    ImageView iv_image_top;

    private void initHeader() {
//        iv_image_top.setBackgroundResource(R.drawable.xiaoli_device_header);
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
//        imageView.setLayoutParams(layoutParams);
        iv_image_top.setOnClickListener(view -> {
//            String packageName = "com.itboye.lingshou";
//            String yinyongbaoPackageName = "com.tencent.android.qqdownloader";
//            Uri uri = Uri.parse("market://details?id=" + packageName);
//            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//            if (WebUtil.checkPackage(yinyongbaoPackageName)) {
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.setPackage(yinyongbaoPackageName);
//            } else {
//                MAlert.alert("检测到你没有安装应用宝，请先下载应用宝");
//                intent = new Intent(DeviceActivity.this, WebActivity.class);
//                intent.putExtra("url", Const.TENCENT_YINGYONGBAO_URL);
//            }
//            startActivity(intent);
        });
//        mListView.addHeaderView(imageView);
    }

    private SpannableString getClickableSpan() {

        //监听器
        View.OnClickListener listener = v -> {
            Uri uri = Uri.parse(Const.PONDLINK_XIYI_URL);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        };
        SpannableString spanableInfo = new SpannableString(Html.fromHtml(htmlText2));
        int start = Html.fromHtml(htmlText2).toString().indexOf("WWW");  //超链接起始位置
        int end = Html.fromHtml(htmlText2).toString().lastIndexOf("M");   //超链接结束位置
        //可以为多部分设置超链接
        spanableInfo.setSpan(new Clickable(listener), start, end + 1, Spanned.SPAN_MARK_MARK);
        return spanableInfo;
    }

    class Clickable extends ClickableSpan implements View.OnClickListener {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener listener) {
            mListener = listener;
        }

        @Override
        public void onClick(View view) {
            mListener.onClick(view);
        }

    }

//    public void showPushMessage() {
//        mApp.showPushMessage(this, ummessage);
//    }

    @Override
    protected void onResume() {
        super.onResume();
        getDeviceList();
    }

    private void initSwipListView() {
        SwipeMenuCreator creator = menu -> {
            // TODO Auto-generated method stub
            SwipeMenuItem deleteItem = new SwipeMenuItem(DeviceActivity.this);
            // set item background
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)));
            deleteItem.setTitle(getString(R.string.delete));
            deleteItem.setTitleColor(Color.WHITE);
//				// set item width
            deleteItem.setWidth(dp2px(90));
            deleteItem.setTitleSize(18);
//				// set a icon
//				deleteItem.setIcon(R.drawable.ic_delete);
//				deleteItem.setBackground(R.drawable.delete_list_item_bg);
            // add to menu
            menu.addMenuItem(deleteItem);
        };

//        mListView.setMenuCreator(creator);
//        mListView.setOnMenuItemClickListener((position, menu, index) -> {
//            switch (index) {
//                case 0:
////					ShopCarBean model=new ShopCarBean();
////					model.setId(dataList.getList().get(position).getId());
////					carPresenter.delete(model);
////                        MAlert.alert("删除了");
//                    // open
////					open(item);
//                    //删除设备操作
//                    loadingDialogDelete = new SureDeleteDialog(DeviceActivity.this, getString(R.string.tips), getString(R.string.make_sure_delete), getString(R.string.cancel), getString(R.string.ok), 0);
//                    loadingDialogDelete.setCanceledOnTouchOutside(false);
//                    loadingDialogDelete.show();
//                    loadingDialogDelete.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(v -> {
//                        loadingDialogDelete.setMessage(getString(R.string.delete_ing));
//                        loadingDialogDelete.getButton(DialogInterface.BUTTON_POSITIVE).setVisibility(View.GONE);
//                        mSelectDeviceInfo = arrayList.get(position);
//                        userPresenter.deleteDevice(arrayList.get(position).getId(), getSp(Const.UID));
//                    });
//                    loadingDialogDelete.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(v -> loadingDialogDelete.dismiss());
//                    break;
//                case 1:
//                    // delete
////					delete(item);
////					mAppList.remove(position);
////					mAdapter.notifyDataSetChanged();
//                    break;
//            }
//        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    public void getDeviceList() {
        userPresenter.getMyDeviceList(uid);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @SuppressLint("WrongConstant")
    public void refreshDeviceListTest() {
//        ArrayList<HashMap<String, Object>> listItemsTemp = buildArrayForMap(arrayList, null);
        mListView.setVisibility(View.VISIBLE);
        relyout.setVisibility(View.VISIBLE);
        deviceListAdapter.notifyDataSetChanged();
        if (arrayList.size() > 0) {
            mListView.setVisibility(View.VISIBLE);
            relyout.setVisibility(View.VISIBLE);
            nodata.setVisibility(View.GONE);
        } else {
            nodata.setVisibility(View.VISIBLE);
        }
        try {
            mSelectDeviceInfo = arrayList.get(position);
        } catch (Exception e) {
            mSelectDeviceInfo = new DeviceListBean();
        }

//        if (mApp.phJiaoZhunUI != null) {
//            //更新APH校准时间
//            mApp.phJiaoZhunUI.setJiaoZhunTimes();
//        }
    }


    protected void onStop() {
        mProgressDialog.dismiss();
        super.onStop();
    }

    Button btn_addnew;

    @Override
    public void onClick(View v) {
        Intent intent = null;
        AlertDialog.Builder alert = null;
        Intent intentWeb = new Intent();
        switch (v.getId()) {
//            case R.id.txt_title:
////                new AsycTask("http://cdn-sunsunxiaoli-com.oss-cn-beijing.aliyuncs.com/S10X0000000001/6").execute();
//                intentWeb = new Intent(this, WebActivity.class);
//                intentWeb.putExtra("title", "ConfigInfo");
//                intentWeb.putExtra("url", "file:///android_asset/html/config_detail.html");
//                startActivity(intentWeb);
//                break;
//            case R.id.txt_ceshu:
//                intentWeb = new Intent(this, WebActivity.class);
//                intentWeb.putExtra("title", getString(R.string.velocity));
//                intentWeb.putExtra("url", "http://" + Const.xiaoli_wrapUrl + "/web.php/net/index.html");
//                startActivity(intentWeb);
//                break;
            case R.id.imageView_dev_right_arrow:
                position = (int) v.getTag();
                longClickEvent(position);
                break;
            case R.id.img_right:
            case R.id.btn_addnew:
//                testDecode();
                    intent = new Intent(this, AddPondDevice.class);
                    intent.putExtra("device_type", "S01");
                    startActivity(intent);
                break;
            case R.id.txt_exist:
//                testEncodeDecode();
                alert = new AlertDialog.Builder(this);
                alert.setMessage(getString(R.string.make_sure_exit));
                alert.setPositiveButton(getString(R.string.ok), (dialog, which) -> deleteUserInfo());
                alert.setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
//                        alert.
                });
                alert.create();
                alert.show();
                break;
        }
    }

    private void deleteUserInfo() {
//        mApp.getInstance().mPushAgent.removeAlias(getSp(Const.UID), BuildConfig.UMENG_ALIAS, (b, s) -> System.out.println(b + "  222  " + s));
        SPUtils.put(this, null, Const.UID, "");
        SPUtils.put(this, null, Const.EMAIL, "");
        SPUtils.put(this, null, Const.PaySecret, "");
        SPUtils.put(this, null, Const.USERNAME, "");
        SPUtils.put(this, null, Const.PASSWORD, "");
        SPUtils.put(this, null, Const.MOBILE, "");
        SPUtils.put(this, null, Const.IS_LOGINED, false);
        SPUtils.put(this, null, Const.HEAD, "");
        SPUtils.put(this, null, Const.NICK, "");
        SPUtils.put(this, null, Const.USER_DEVICE_NUMBER, "");
        SPUtils.put(this, null, Const.S_ID, "");
        SPUtils.put(this, null, Const.INVITE_CODE, "");
        LoginController.setLoginState(new UnLoginState());
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void update(Observable o, Object data) {
        ResultEntity entity = handlerError(data);
        try {
            //停止刷新
            swipe_layout.setRefreshing(false);
            closeProgressDialog();
        } catch (Exception e) {

        }
        if (entity != null) {
            if (entity.getCode() != 0) {
                try {
                    new Handler().postDelayed(() -> {
                        if (loadingDialog != null) {
                            setDialoadDismiss(loadingDialog);
                        }
                        if (loadingDialogDelete != null) {
                            loadingDialogDelete.dismiss();
                        }
                    }, 2000);
                } catch (Exception e) {

                }
                MAlert.alert(entity.getMsg());
            } else if (entity.getEventType() == UserPresenter.getMyDeviceList_success) {
                arrayList.clear();
                arrayList.addAll((ArrayList<DeviceListBean>) entity.getData());
                refreshDeviceListTest();
            } else if (entity.getEventType() == UserPresenter.getMyDeviceList_fail) {
                MAlert.alert(entity.getMsg());
            } else if (entity.getEventType() == UserPresenter.deleteDevice_success) {
                loadingDialogDelete.setMessage(entity.getData() + "");
                new Handler().postDelayed(() -> loadingDialogDelete.dismiss(), 2000);
                getDeviceList();
            } else if (entity.getEventType() == UserPresenter.deleteDevice_fail) {
                loadingDialogDelete.setMessage(entity.getMsg() + "");
                new Handler().postDelayed(() -> loadingDialogDelete.dismiss(), 2000);
            } else if (entity.getEventType() == UserPresenter.authDevicePwdsuccess) {
                startDeviceUI(true);
            } else if (entity.getEventType() == UserPresenter.authDevicePwdfail) {
                loadingDialog.setMessage(entity.getData() + "");
                new Handler().postDelayed(() -> setDialoadDismiss(loadingDialog), 2000);
            } else if (entity.getEventType() == UserPresenter.getdeviceinfosuccess) {
                deviceDetailModel = (DeviceDetailModel) entity.getData();
                if (deviceDetailModel == null) {
                    loadingDialog.setMessage(getString(R.string.get_device_status_fail));
                    new Handler().postDelayed(() -> setDialoadDismiss(loadingDialog), 2000);
                    return;
                } else {
//                    loadingDialog.setMessage(getString(R.string.get_device_status_success));
                    if (!deviceDetailModel.getIs_disconnect().equals("0")) {
                        loadingDialog.setMessage(getString(R.string.device) + getString(R.string.offline));
                        new Handler().postDelayed(() -> setDialoadDismiss(loadingDialog), 2000);
//                        return;
                    }
                }
                String psw;
                try {
                    JSONObject jsonObject = new JSONObject(mSelectDeviceInfo.getExtra());
                    psw = jsonObject.getString("pwd");
                    if (psw.equals("")) {
                        psw = "sunsun123456";
                    }
                } catch (JSONException e) {
                    psw = "sunsun123456";
                }
                System.out.println("设备密码" + psw);
//                startDeviceUI(true);
                userPresenter.authDevicePwd(currentDid, psw, currentType);
            } else if (entity.getEventType() == UserPresenter.getdeviceinfofail) {
                MAlert.alert(entity.getMsg());
                new Handler().postDelayed(() -> setDialoadDismiss(loadingDialog), 2000);
            } else if (entity.getEventType() == get_onLine_state) {
                deviceDetailModel = (DeviceDetailModel) entity.getData();
                //如果携带了字母
                //在线且版本号低于1.4
                float version = subVersion(deviceDetailModel.getVer(), ComparePondFilterVersion.isTrue(deviceDetailModel.getVer()));
                if (version < 1.4f) {
                    setDialoadDismiss(loadingDialog);
                    Intent intent = new Intent(DeviceActivity.this, PondTeamVersionUpdateActivity.class);
                    intent.putExtra("version", deviceDetailModel.getVer());
                    intent.putExtra("did", deviceDetailModel.getDid());
                    startActivity(intent);
                } else {
                    //大于1.4版本的可以正常使用新域名
                    if (!deviceDetailModel.getIs_disconnect().equals("0")) {
                        loadingDialog.setMessage(getString(R.string.disconnect));
                        new Handler().postDelayed(() -> setDialoadDismiss(loadingDialog), 2000);
                        return;
                    }
                    startDeviceUI(true);
                }

            } else if (entity.getEventType() == UserPresenter.shareDeviceCommentAdd_success) {
                MAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.shareDeviceCommentAdd_fail) {
                MAlert.alert(entity.getMsg());
            }
        }
    }

    private void setDialoadDismiss(ProgressDialog loadingDialog) {
        try {
            if (loadingDialog != null && loadingDialog.isShowing() && !this.isFinishing() && this != null) {
                loadingDialog.dismiss();
            }
        } catch (Exception e) {

        }
    }

    private void startDeviceUI(final boolean hasPsw) {
//        loadingDialog.setMessage(getString(R.string.yanzheng_success));
        new Handler().postDelayed(() -> {
            setDialoadDismiss(loadingDialog);
            Intent intent = null;
            String deviceType = mSelectDeviceInfo.getDevice_type();
            if (deviceType.contains("S01")) {
                //过滤桶
                    intent = new Intent(DeviceActivity.this, ActivityPondDeviceDetail.class);
            } else {
                MAlert.alert(getString(R.string.no_support_device));
                return;
            }
            intent.putExtra("title", mSelectDeviceInfo.getDevice_nickname());
            intent.putExtra("did", mSelectDeviceInfo.getDid());
            intent.putExtra("id", mSelectDeviceInfo.getId());
            intent.putExtra("hasPsw", hasPsw);//无密码则应该重新进入插入密码
            intent.putExtra("detailModel", deviceDetailModel);
            startActivityForResult(intent, 101);
        }, 2000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 102) {
            getDeviceList();
        }
    }

    @Override
    public void onRefresh() {
        getDeviceList();
    }
}
